package cn.xinfei.xdecision.engine.api;

import cn.xinfei.xdecision.common.utils.util.JsonUtils;
import cn.xinfei.xdecision.engine.runner.api.DecisionExamApi;
import cn.xinfei.xdecision.engine.runner.context.XDecisionContext;
import cn.xinfei.xdecision.model.DecisionExamComponentApiRequest;
import cn.xinfei.xdecision.model.DecisionExamNodeApiRequest;
import cn.xinfei.xdecision.model.DecisionExamApiResponse;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("engine/exam")
public class XDecisionExamApi {

    @Autowired
    private DecisionExamApi decisionExamApi;


    /**
     * 节点测试接口
     *
     * @param apiRequest
     * @return
     */
    @RequestMapping(value = "/node", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "节点测试接口")
    public DecisionExamApiResponse node(@RequestBody DecisionExamNodeApiRequest apiRequest) {
        log.info("node request:{}", JsonUtils.toJsonString(apiRequest));
        DecisionExamApiResponse execute = null;
        try {
            execute = decisionExamApi.executeNode(apiRequest);
            XDecisionContext.destroy();
        } catch (Exception e) {
            log.error("决策接口异常，error={},apiRequest={}", e.getMessage(), JsonUtils.toJsonString(apiRequest), e);
        }
        return execute;
    }


    /**
     * 组件测试接口
     *
     * @param apiRequest
     * @return
     */
    @ApiOperation(value = "组件测试接口")
    @RequestMapping(value = "/component", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public DecisionExamApiResponse component(@RequestBody DecisionExamComponentApiRequest apiRequest) {
        log.info("component request:{}", JsonUtils.toJsonString(apiRequest));
        DecisionExamApiResponse execute = null;
        try {
            execute = decisionExamApi.executeComponent(apiRequest);
            XDecisionContext.destroy();
        } catch (Exception e) {
            log.error("决策接口异常，error={},apiRequest={}", e.getMessage(), JsonUtils.toJsonString(apiRequest), e);
        }
        return execute;
    }
}
